<?php
namespace App\Http\Controllers\Passenger\V2\Order;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderFlow;
use App\Models\Orders;
use App\Models\RefundOrder;
use Illuminate\Support\Facades\DB;
use Overtrue\LaravelWeChat\Facade;

class RefundNotifyController extends Controller
{


    /**
     * 微信退款
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function weixin()
    {

        $payment = Facade::payment();

        $response = $payment->handleRefundedNotify(function ($message, $reqInfo, $fail) {

            // 根据返回的订单号查询订单数据
            $refund_order_info = RefundOrder::query()->firstWhere('sn', $reqInfo['out_refund_no']);

            if (!$refund_order_info)
                $fail('Refund Order not exist.');

            if($refund_order_info->status == 2)
                return true;

            $order_info = Orders::query()->find($refund_order_info->order_id);

            if (!$refund_order_info)
                $fail('Order not exist.');


            if ($refund_order_info->status != 1) {
                return true;
            }

            // 退款成功后的业务逻辑
            if ($reqInfo['refund_status'] === 'SUCCESS') {
                DB::beginTransaction();
                $refund_order_info->status       = 2;
                $refund_order_info->refund_sn    = $reqInfo['refund_id'];
                $refund_order_info->success_time = strtotime($reqInfo['success_time']);
                $refund_order_info->refund_data  = json_encode($reqInfo);

                if (!$refund_order_info->save()) {
                    $fail('Refund Order Error');
                }

                if ($refund_order_info->type == 1) { //乘客取消退款
                    $order_info->cancel_status = 0;
                }

//                if ($refund_order_info->type == 2) { //服务结束退款
//                    $order_info->status = '5';
//                }
                $order_info->real_price = $order_info->real_price - ($reqInfo['refund_fee'] / 100);
                if ($order_info->save() === false) {
                    DB::rollBack();
                    $fail('Order Error');
                }

                $order_flow = new OrderFlow();
                $order_flow->user_id  = $order_info->user_id;
                $order_flow->order_id = $order_info->id;
                $order_flow->order_sn = $order_info->order_sn;
                $order_flow->pay_sn   = $reqInfo['refund_id'];
                $order_flow->price    = -$reqInfo['refund_fee'] / 100;
                if ($order_flow->save() === false) {
                    DB::rollBack();
                    $fail('Order Flow Error');
                }

                //todo 呼叫车辆
                DB::commit();
            }

            return true;
        });

        return $response;
    }

}
